package report.service.dashboard.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import report.dao.po.DashboardTreeDO;
import report.dao.po.ReportTreeDO;
import report.dao.repository.DashboardTreeRepository;
import report.dao.vo.tree.DashboardTreeVO;
import report.dao.vo.tree.TreeVO;
import report.service.dashboardTree.IDashboardTreeService;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DashboardTreeServiceImpl implements IDashboardTreeService {

    @Autowired
    private DashboardTreeRepository dashboardTreeRepository;

    @Override
    public DashboardTreeVO getTree(String id) {
        return null;
    }

    @Override
    // 获取所有目录
    public List<DashboardTreeVO> getTree() {
        // 从根节点开始
        List<DashboardTreeDO> dos = dashboardTreeRepository.findAll();
        List<DashboardTreeVO> ret = fn(dos,"0");
        return  ret;

    }


    // 一个递归函数
    private List<DashboardTreeVO> fn(List<DashboardTreeDO> data, String pid){

        return data.stream().filter(d->d.getTypeCode().equals("0") && d.getPid().equals(pid)).map(it->{
            DashboardTreeVO dashboardTreeVO= DashboardTreeVO.do2vo(it);
            List<DashboardTreeVO> children = fn(data,dashboardTreeVO.getId());
            if(children.size()>0){
                dashboardTreeVO.setChildren(children);
            }
            return dashboardTreeVO;
        }).collect(Collectors.toList());


    }

    /**
     * 创建目录
     * @param pid
     * @param name
     * @return
     */
    public String createCata(String pid, String name){
        DashboardTreeDO dashboardTreeVO  = new DashboardTreeDO();
        dashboardTreeVO.setPid(pid);
        dashboardTreeVO.setName(name);
        dashboardTreeVO.setTypeCode("0");

        dashboardTreeRepository.save(dashboardTreeVO);

        return "success";
    }

    /**
     * 更新目录
     * @param id
     * @param pid
     * @param name
     * @return
     */
    public String updateCata(String id, String pid, String name){
        DashboardTreeDO dashboardTreeVO  = new DashboardTreeDO();
        dashboardTreeVO.setPid(pid);
        dashboardTreeVO.setName(name);
        dashboardTreeVO.setId(id);
        dashboardTreeVO.setTypeCode("0");

        dashboardTreeRepository.saveAndFlush(dashboardTreeVO);

        return "success";
    }

    /**
     * 删除目录，以及下面所有目录和报表
     * @param id
     * @return
     */
    public String deleteCata(String id){
        // 删除自己
        dashboardTreeRepository.delete(id);
        // 删除子节点
        List<DashboardTreeDO> dos = dashboardTreeRepository.findAllByPid(id);
        dashboardTreeRepository.deleteInBatch(dos);

        return "success";
    }
}
